//
//  PatrolDetailViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/10/31.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "PatrolTimeCell.h"
#import "UIActionSheet+Common.h"
#import "ActionSheetDatePicker.h"
// 附件
#import "H1_ImagesCell.h"
#import "PictureViewController.h"

// 巡视时间Cell
#import "PatrolTimeCell.h"


// 巡视模型
#import "PatrolRecord.h"
// 显示cell
#import "DefaineCell.h"
// 单行输入cell
#import "QianDTableCell.h"
// 多行输入cell
#import "B_wuLiaoCell.h"
// 位置cell
#import "PositionTableCell.h"
// 位置控制器
#import "OrientationViewController.h"

#import "PatrolDetailViewController.h"

@interface PatrolDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

// 表格
@property (strong, nonatomic) TPKeyboardAvoidingTableView *tableView;
// 施工合同段
@property (strong, nonatomic) DefaineCell *segmentCell;
// 天气cell
@property (strong, nonatomic) DefaineCell *weatherCell;
/**添加的巡视时间数组*/
@property (strong, nonatomic) NSMutableArray *addPatrolTimeArr;


// 附件模型
@property (strong, nonatomic) Tweet *curTweet;
// 图片路径数组
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;


#pragma MARK - 位置信息记录
// 记录各级数据源
@property (strong, nonatomic) NSMutableArray *dataArr1;
@property (strong, nonatomic) NSMutableArray *dataArr2;
@property (strong, nonatomic) NSMutableArray *dataArr3;
@property (strong, nonatomic) NSMutableArray *dataArr4;
// block参数
@property (strong, nonatomic) PositionBlockModel *blockModel;
// 当前被点的地址数据模型
@property (strong, nonatomic) AddressModel *addressModel;

// 是否可编辑
@property (assign, nonatomic) BOOL isEdit;
//天气地区
@property (strong, nonatomic)NSMutableArray *weatherArr;
@end

@implementation PatrolDetailViewController

// 添加的巡视时间数组
- (NSMutableArray *)addPatrolTimeArr {
    if (!_addPatrolTimeArr) {
        _addPatrolTimeArr = [[NSMutableArray alloc] init];
    }
    return _addPatrolTimeArr;
}

// 附件图片数组
- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (TPKeyboardAvoidingTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColorFromRGB(0xf2f2f2);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorColor = UIColorFromRGB(0xeeeeee);
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
        
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"bCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defineCell"];
        [_tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"positionCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PatrolTimeCell" bundle:nil] forCellReuseIdentifier:@"PatrolTimeCell"];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"巡视";
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.isEdit = YES;
    self.weatherArr = [LSUtility getWeatherArea];
    if (self.patrolModel.weather && ![self.patrolModel.weather isEqualToString:@""]) {
        NSArray  *weathers = [self.patrolModel.weather componentsSeparatedByString:@"/"];
        self.patrolModel.areaStr = weathers[0];
        self.patrolModel.weather = weathers[1];
    }
    // 是否可编辑
    if (self.isDiary) {
        self.isEdit = NO;
        
    } else {
        [self isEditable];
        if (self.isEdit) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveData)];
        }
    }
    
    //附件模型
    _curTweet = [[Tweet alloc] init];
    [self.view addSubview:self.tableView];
    
    // 巡视时间
    if (self.patrolModel.startAndEndTime && ![self.patrolModel.startAndEndTime isEqualToString:@""]) {
        NSData *fileinfosData = [self.patrolModel.startAndEndTime dataUsingEncoding:NSASCIIStringEncoding];
        NSArray *timeArr = [LSUtility toArrayOrNSMutableDictionary:fileinfosData];
        [self.addPatrolTimeArr addObjectsFromArray:timeArr];
    }
    
    // 查找附件数据
    [self initDataSource];
    // 附件通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_patrol" object:nil];
}

// 是否可编辑判定
- (void)isEditable {
    // 巡视创建时间
    NSString *createStr = [self.patrolModel.createtime substringToIndex:10];
    // 获取当下日期
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [formatter stringFromDate:currentDate];
    
    // 查找今天的日记
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM WORK_DIARY WHERE date(CREATE_TIME) = '%@'", dateStr];
    // 是否生成日记
    BOOL isBeDiary = NO;
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSString *patrolInfo = [result stringForColumn:@"PATROL_RECORD_INFO"];
        NSData *nsData = [patrolInfo dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *patrolArr = [NSJSONSerialization JSONObjectWithData:nsData options:kNilOptions error:nil];
        for (NSDictionary *dic in patrolArr) {
            if ([dic[@"recordId"] isEqualToString:self.patrolModel.id]) {
                isBeDiary = YES;
            }
        }
    }
    [db close];
    self.isEdit = ([createStr isEqualToString:dateStr] && !isBeDiary);
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        });
    }
}

// 查找附件数据
- (void)initDataSource {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 查找附件信息
    NSString *attachmentStr = [NSString stringWithFormat:@"SELECT * FROM ATTACHMENT WHERE FILE_ID = '%@' ORDER BY CREATE_TIME desc", self.patrolModel.id];
    FMResultSet *attachmentResult = [db executeQuery:attachmentStr];
    while ([attachmentResult next]) {
        // 图片名
        NSString *fileName = [attachmentResult stringForColumn:@"FILE_NAME"];
        NSString *filePath = [DEF_FILE_PATH stringByAppendingString:
                              [NSString stringWithFormat:@"/%@",fileName]];
        [self.selectedAssetURLs addObject:filePath];
    }
    [db close];
    self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
    [self.tableView reloadData];
}

#pragma MARK - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
        
    } else {
        return 0.01;
    }
}



// 添加巡视时间
- (void)addTime {
    NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
    [mDic setObject:@"" forKey:@"start_time"];
    [mDic setObject:@"" forKey:@"end_time"];
    [self.addPatrolTimeArr addObject:mDic];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //    if (section == 0) {
    //        return self.addPatrolTimeArr.count+1;
    //
    //    } else
    if (section == 0) {
        return 11;
        
    } else if (section == 1) {
        return 4;
        
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    if (section == 0) {
        return 44;
        
    } else if (section == 1) {
        return 120;
        
    } else {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"添加照片"];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
   
    if (section == 0) {
        // 项目名称
        if (row == 0) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"项目名称";
            defineCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
            return defineCell;
            
            // 监理单位
        } else if (row == 1) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"监理单位";
            
            // 查找监理单位
            NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
            FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
            [db open];
            FMResultSet *result = [db executeQuery:sqlStr];
            while ([result next]) {
                // 单位名称
                NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
                self.patrolModel.supervisorProUnitName = proName;
                // 单位ID
                self.patrolModel.supervisorProUnitId = [result stringForColumn:@"ID"];
                defineCell.text.text = proName;
            }
            [db close];
            return defineCell;
            
            // 施工单位
        } else if (row == 2) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            defineCell.title.text = @"施工单位";
            defineCell.text.text = self.patrolModel.constructProUnitName ? self.patrolModel.constructProUnitName : @"请选择施工单位";
            return defineCell;
            
            // 编号
        } else if (row == 3) {
            QianDTableCell *qianCell = [tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            qianCell.isedit = self.isEdit;
            qianCell.title.text = @"编号            ";
            qianCell.textField.placeholder = @"请输入记录编号";
            if (self.patrolModel.recordNumber && ![self.patrolModel.recordNumber isEqualToString:@""]) {
                qianCell.textField.text = self.patrolModel.recordNumber;
            }
            qianCell.textValueChangedBlock = ^(NSString *str) {
                self.patrolModel.recordNumber = str;
            };
            return qianCell;
            
            // 监理合同段
        } else if (row == 4) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"监理合同段";
            // 查找监理合同段
            NSString *sqlStr = [NSString stringWithFormat:@"SELECT CONTRCT_NUMBER FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
            FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
            [db open];
            FMResultSet *result = [db executeQuery:sqlStr];
            while ([result next]) {
                NSString *contrctNumber = [result stringForColumn:@"CONTRCT_NUMBER"];
                defineCell.text.text = contrctNumber;
                // 记录监理合同段
                self.patrolModel.supervisorContractNumber = contrctNumber;
            }
            [db close];
            return defineCell;
            
            // 施工合同段
        } else if (row == 5) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            self.segmentCell = defineCell;
            defineCell.title.text = @"施工合同段";
            return defineCell;
            
            // 所在区域
        } else if (row == 6) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            defineCell.title.text = @"所在区域";
            if (self.patrolModel.areaStr && ![self.patrolModel.areaStr isEqualToString:@""]) {
                defineCell.text.text = self.patrolModel.areaStr;
                
            }else {
                defineCell.text.text = @"请选择所在区域";
            }
            return defineCell;
            
            // 天气
        } else if (row == 7) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.text.text = _patrolModel.weather;
            defineCell.title.text = @"天气";
            return defineCell;
            
            // 工程地点
        } else if (row == 8) {
            PositionTableCell *positionCell =[tableView dequeueReusableCellWithIdentifier:@"positionCell" forIndexPath:indexPath];
            positionCell.isEdit = self.isEdit;
            positionCell.title.text = @"工程地点";
            
            if (self.patrolModel.addInfo == nil || [self.patrolModel.addInfo isEqualToString:@""]) {
                positionCell.btnStr = @"请选择工程地点";
            } else {
                NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.patrolModel.addInfo];
                positionCell.btnStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"leftDistanceStr"]];
            }
            
            
            // 位置cell的Block
            positionCell.cliclWzBlock = ^{
                OrientationViewController *location=[[OrientationViewController alloc]init];
                location.flagStr = @"jilu";
                location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr3];
                location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr4];
                location.aID = self.blockModel.aID;
                location.firstID = self.blockModel.firstID;
                location.secondID = self.blockModel.secondID;
                location.thirdID = self.blockModel.thirdID;
                
                location.keyStr = self.blockModel.keyStr;
                location.number = self.blockModel.number;
                location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];
                location.position = self.blockModel.position;
                location.addressModel = self.addressModel;
                location.selectedX = self.blockModel.selectedX;
                location.selectedY = self.blockModel.selectedY;
                location.scale = self.blockModel.scale;
                
                if (location.number) {
                    location.hC = YES;
                }
                
                [self.navigationController pushViewController:location animated:YES];
                // 回传位置值
                location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr){
                    self.blockModel = model;
                    self.addressModel = addModel;
                    self.patrolModel.addId = model.aID;
                    self.patrolModel.addInfo = addInfoStr;
                    
                    // 刷新位置值
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:8 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                };
            };
            return positionCell;
            
            // 核查日期
        } else if (row == 9) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"核查日期";
            
            // 获取当下日期
            NSDate *currentDate = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            NSString *dateStr = [formatter stringFromDate:currentDate];
            defineCell.text.text = dateStr;
            return defineCell;
            
            // 核查人员
        } else {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"核查人员";
            defineCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"realname");
            return defineCell;
        }
    } else if (section == 1) {
        B_wuLiaoCell *bCell = [tableView dequeueReusableCellWithIdentifier:@"bCell" forIndexPath:indexPath];
        bCell.isEdit = self.isEdit;
        
        // 巡视的范围
        if (row == 0) {
            bCell.title.text = @"巡视的范围:";
            if (self.patrolModel.rangeAndPosition && ![self.patrolModel.rangeAndPosition isEqualToString:@""]) {
                bCell.text.text = self.patrolModel.rangeAndPosition;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.patrolModel.rangeAndPosition = valueStr;
            };
            
            // 主要施工情况
        } else if (row == 1) {
            bCell.title.text = @"主要施工情况:";
            if (self.patrolModel.majorproAndPerson && ![self.patrolModel.majorproAndPerson isEqualToString:@""]) {
                bCell.text.text = self.patrolModel.majorproAndPerson;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.patrolModel.majorproAndPerson = valueStr;
            };
            
            // 巡检人主要巡检数据记录
        } else if (row == 2) {
            bCell.title.text = @"质量、安全、环保等情况:";
            if (self.patrolModel.majorInspectData && ![self.patrolModel.majorInspectData isEqualToString:@""]) {
                bCell.text.text = self.patrolModel.majorInspectData;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.patrolModel.majorInspectData = valueStr;
            };
            
            // 巡检人发现的问题及主要情况简述
        } else {
            bCell.title.text = @"发现的问题及处理意见:";
            if (self.patrolModel.problemAndDeal && ![self.patrolModel.problemAndDeal isEqualToString:@""]) {
                bCell.text.text = self.patrolModel.problemAndDeal;
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.patrolModel.problemAndDeal = valueStr;
            };
        }
        return bCell;
        
    } else {
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit = self.isEdit;
        [cell setTitle:@"添加照片"];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        return cell;
    }
}
// 巡视时间
- (void)selectTime:(UIButton *)valueBtn {
    if (!self.isEdit) {
        return;
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date = [NSDate date];
    ActionSheetDatePicker *picker = [[ActionSheetDatePicker alloc] initWithTitle:nil datePickerMode:UIDatePickerModeTime selectedDate:date doneBlock:^(ActionSheetDatePicker *picker, NSDate *selectedDate, id origin) {
        NSString *dateStr = [dateFormatter stringFromDate:selectedDate];
        [dateFormatter setDateFormat:@"HH:mm"];
        //修改数据
        [valueBtn setTitle:[dateFormatter stringFromDate:selectedDate] forState:UIControlStateNormal];
        if (valueBtn.tag == 10000) {
            self.patrolModel.startTime = dateStr;
        } else if (valueBtn.tag == 9999) {
            self.patrolModel.endTime = dateStr;
        } else if (valueBtn.tag > 10000) {
            if (self.addPatrolTimeArr.count > 0) {
                NSInteger i = valueBtn.tag - 10000;
                NSMutableDictionary *mDic = self.addPatrolTimeArr[i-1];
                mDic[@"start_time"] = dateStr;
            }
        } else if (valueBtn.tag <9999) {
            if (self.addPatrolTimeArr.count > 0) {
                NSInteger i = 9999 - valueBtn.tag;
                NSMutableDictionary *mDic = self.addPatrolTimeArr[i-1];
                mDic[@"end_time"] = dateStr;
            }
        }
    } cancelBlock:nil origin:self.view];
    
    if (valueBtn.tag == 10000) {
        // 最大值
        NSDate *maxdate = [dateFormatter dateFromString:self.patrolModel.endTime];
        picker.maximumDate = maxdate;
        
    } else if (valueBtn.tag == 9999) {
        // 最小值
        NSDate *mindate = [dateFormatter dateFromString:self.patrolModel.startTime];
        if(mindate){
            picker.minimumDate = mindate;
        }
        
    } else if (valueBtn.tag > 10000) {
        if (self.addPatrolTimeArr.count > 0) {
            NSInteger i = valueBtn.tag - 10000;
            NSMutableDictionary *mDic = self.addPatrolTimeArr[i-1];
            //最大值
            NSDate *maxdate = [dateFormatter dateFromString:mDic[@"end_time"]];
            picker.maximumDate = maxdate;
        }
        
    } else if (valueBtn.tag <9999) {
        if (self.addPatrolTimeArr.count > 0) {
            NSInteger i = 9999 - valueBtn.tag;
            NSMutableDictionary *mDic = self.addPatrolTimeArr[i-1];
            // 最小值
            NSDate *mindate = [dateFormatter dateFromString:mDic[@"start_time"]];
            picker.minimumDate = mindate;
            if(mindate){
                picker.minimumDate = mindate;
            }
        }
    }
    [picker showActionSheetPicker];
}

-(void)deleteTime:(UIButton *)button{
    if (!self.isEdit) {
        return;
    }
    [self.addPatrolTimeArr removeObjectAtIndex:button.tag-100000-1];
    [self.tableView reloadData];
}

#pragma MARK - didSelectRowAtIndexPath(选择信息)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.isEdit) {
        NSInteger section = indexPath.section;
        NSInteger row = indexPath.row;
        if (section == 0) {
            // 选择施工单位
            if (row == 2) {
                // 查找施工单位列表
                NSArray *constructionUnitArr = [self getConstructionUnitList];
                if (constructionUnitArr.count > 0) {
                    NSMutableArray *arr = [NSMutableArray array];
                    NSNumber *ninit = [NSNumber numberWithInteger:0];
                    for (NSDictionary *dic in constructionUnitArr) {
                        [arr addObject:dic[@"NAME"]];
                    }
                    [ActionSheetStringPicker showPickerWithTitle:nil rows:@[arr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray *selectedIndex, NSArray *selectedValue) {
                        
                        // 修改数据
                        DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                        cell.text.text = [selectedValue firstObject];
                        NSInteger index = [[selectedIndex firstObject] integerValue];
                        NSDictionary *constructionUnitDic = constructionUnitArr[index];
                        [self checkConstruction:constructionUnitDic[@"ID"]];
                        // 暂存施工单位ID
                        DEF_PERSISTENT_SET_OBJECT(constructionUnitDic[@"ID"], @"constructionUnitID");
                        
                        // 要保存的施工单位信息
                        self.patrolModel.constructProUnitId = constructionUnitDic[@"ID"];
                        self.patrolModel.constructProUnitName = constructionUnitDic[@"NAME"];
                        
                    } cancelBlock:nil origin:self.view];
                    
                } else {
                    [LSUtility showToastWithMessage:@"数据为空" inView:self.view Andtime:1.0];
                }
                
                // 选择地区
            } else if (row == 6) {
                NSNumber *ninit = [NSNumber numberWithInteger:0];
                NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
                if(!wArr){
                    wArr=[NSMutableArray arrayWithObject:@{@"无":@"暂时无法获得天气信息"}];
                }
                if(self.weatherArr.count<1){
                    [self.weatherArr addObject:@"无"];
                }
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[self.weatherArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                    int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                    NSDictionary *weadic=wArr[iv];
                    NSString *address =self.weatherArr[iv];
                    self.patrolModel.areaStr=address;
                    self.patrolModel.weather=weadic[address];
                    //刷新城市、刷新天气
                    NSIndexPath *windexPath=[NSIndexPath indexPathForRow:7 inSection:0];
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath,windexPath] withRowAnimation:UITableViewRowAnimationNone];
                    
                } cancelBlock:nil origin:self.view];
                
            }
        }
    }
}

// 查找施工单位列表
- (NSArray *)getConstructionUnitList {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_02'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *constructionUnitArr = [NSMutableArray array];
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
        NSString *idStr = [result stringForColumn:@"ID"];
        NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
        [mDic setObject:idStr forKey:@"ID"];
        [mDic setObject:proName forKey:@"NAME"];
        [constructionUnitArr addObject:mDic];
    }
    [db close];
    return constructionUnitArr;
}

// 查找施工合同段及合同金额
- (void)checkConstruction:(NSString *)idStr {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT CONTRCT_NUMBER, CONTRCT_MONEY FROM PROJECT_UNIT WHERE ID = '%@'", idStr];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSString *contrctNumber = [result stringForColumn:@"CONTRCT_NUMBER"];
        self.segmentCell.text.text = contrctNumber;
        // 保存信息
        self.patrolModel.constructContractNumber = contrctNumber;
    }
    [db close];
}

#pragma mark - 新增保存巡视
// 保存数据
- (void)saveData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 字段及对应值
    NSString *weather=[NSString stringWithFormat:@"%@/%@",DEFISNUL(self.patrolModel.areaStr),DEFISNUL(self.patrolModel.weather)];
    
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":DEFISNUL(self.patrolModel.id),
                   @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                   @"SUPERVISOR_PRO_UNIT_ID":DEFISNUL(self.patrolModel.supervisorProUnitId),
                   @"CONSTRUCT_PRO_UNIT_ID":DEFISNUL(self.patrolModel.constructProUnitId),
                   @"SUPERVISOR_PRO_UNIT_NAME":DEFISNUL(self.patrolModel.supervisorProUnitName),
                   @"CONSTRUCT_PRO_UNIT_NAME":DEFISNUL(self.patrolModel.constructProUnitName),
                   @"SUPERVISOR_CONTRACT_NUMBER":DEFISNUL(self.patrolModel.supervisorContractNumber) ,
                   @"CONSTRUCT_CONTRACT_NUMBER":DEFISNUL(self.patrolModel.constructContractNumber),
                   @"RECORD_USER":DEFISNUL(USERID),
                   @"RECORD_TYPE":DEFISNUL(self.patrolModel.recordType),
                   @"RECORD_TITLE":DEFISNUL(self.patrolModel.recordTitle),
                   @"RECORD_CONTENT":DEFISNUL(self.patrolModel.recordContent),
                   @"STATE":DEFISNUL(@"1"),
                   @"RECORD_NUMBER":DEFISNUL(self.patrolModel.recordNumber),
                   @"START_TIME":DEFISNUL(self.patrolModel.startTime),
                   @"END_TIME":DEFISNUL(self.patrolModel.endTime),
                   @"START_AND_END_TIME":DEFISNUL(self.patrolModel.startAndEndTime),
                   @"WEATHER":weather,
                   @"ADD_ID":DEFISNUL(self.patrolModel.addId),
                   @"ADD_INFO":DEFISNUL(self.patrolModel.addInfo),
                   @"RANGE_AND_POSITION":DEFISNUL(self.patrolModel.rangeAndPosition),
                   @"MAJORPRO_AND_PERSON":DEFISNUL(self.patrolModel.majorproAndPerson),
                   @"MAJOR_INSPECT_DATA":DEFISNUL(self.patrolModel.majorInspectData),
                   @"PROBLEM_AND_DEAL":DEFISNUL(self.patrolModel.problemAndDeal),
                   @"EXTEND_INFO":DEFISNUL(self.patrolModel.extendInfo),
                   @"CREATE_USER_NAME":DEFISNUL(self.patrolModel.createusername),
                   @"CREATE_TIME":DEFISNUL(self.patrolModel.createtime),
                   @"CREATE_IP":DEFISNUL(self.patrolModel.createip),
                   @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                   @"MODIFY_TIME":[LSUtility nowTime],
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"MOD",
                   };
    
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PATROL_RECORD];
    if (isAdd) {
        NSLog(@"添加巡视成功");
        
    } else {
        NSLog(@"添加巡视失败");
    }
    // 添加附件
    [self insertAttachment];
}

#pragma mark - 更新附件表
- (void)insertAttachment {
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    // 删除旧附件
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM ATTACHMENT WHERE FILE_ID = '%@'", self.patrolModel.id];
    if ([db executeUpdate:sqlStr]) {
        NSLog(@"删除附件成功");
        
    } else {
        NSLog(@"删除附件失败");
    }
    
    // 重新写入附件
    DBHelper *dbhelper = [DBHelper help];
    for (NSString *imageUrlStr in self.selectedAssetURLs) {
        // 图片
        UIImage *image = [UIImage imageWithContentsOfFile:imageUrlStr];
        
        // filePath
        NSArray *arr = [imageUrlStr componentsSeparatedByString:@"/"];
        NSString *imageName = [arr lastObject];
        NSDate *senddate = [NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyyMMdd"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        //拼接路径
        NSString *filePath = [NSString stringWithFormat:@"/%@/%@.png", locationString, imageName];
        
        NSDictionary *pragameDic = [NSDictionary dictionary];
        pragameDic = @{
                       @"ID":DEFISNUL([NSUUID UUID].UUIDString),
                       //文件所属记录类型
                       @"FILE_TYPE_ID":@"RECORD_PATROL_01",
                       //文件所属记录
                       @"FILE_ID":self.patrolModel.id,
                       //所属项目
                       @"PRO_ID":PROID,
                       //文件名称
                       @"FILE_NAME":imageName,
                       //文件大小
                       @"FILE_SIZE":[LSUtility imageDataLenth:image],
                       //文件后缀名
                       @"FILE_SUFFIX":@".png",
                       //文件路径
                       @"FILE_PATH":filePath,
                       @"FILE_DESC":@"",
                       //附件状态
                       @"FILE_STATE":@"0",
                       //扩展信息
                       @"EXTEND_INFO":@"",
                       //创建人
                       @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                       //创建时间
                       @"CREATE_TIME":[LSUtility dateNow],
                       //创建IP
                       @"CREATE_IP":[LSUtility getIPAddress],
                       @"MODIFY_USER_NAME":@"",
                       @"MODIFY_IP":@"",
                       @"MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"ADD"
                       };
        
        BOOL isAdd = [dbhelper DataBase:db insertReplaceKeyValues:pragameDic intoTable:ATTACHMENT];
        
        if (isAdd) {
            NSLog(@"添加巡视附件成功");
            
        } else {
            NSLog(@"添加巡视附件失败");
        }
    }
    // 刷新巡视列表页
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPatrolList" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UIActionSheet M
- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            //            for (NSString *path in array) {
            //                //添加图片路径到已选数组
            //                [self.selectedAssetURLs addObject:path];
            //            }
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    //判断是否加水印
    BOOL water= [LSUtility isWaterMark];
    //需要打印水印
    if(water){
        NSArray *arr=[LSUtility queryPhotoWaterarkWord];
        //存在水印打印内容
        if(arr&&arr.count>0){
            if([arr containsObject:@"time"]||[arr containsObject:@"TIME"]){
                //                DeLog(@"打水印");
                image=[UIImage imageWithimage:image content:[LSUtility nowTime] frame:CGRectZero];
            }        }
    }
    
    //设置图片名称
    NSString *imageName=[NSString stringWithFormat:@"%@",[LSUtility getCurrentDateString]];
    //存入附件永久文件夹
    [LSUtility saveImagePermanent:image withName:imageName];
    //存入首页临时文件夹
    [LSUtility saveImage:image withName:[NSString stringWithFormat:@"%@",imageName]];
    //得到该照片路径
    NSString *path= [DEF_FILE_PATH stringByAppendingPathComponent:imageName];
    
    [self.curTweet addASelectedAssetURL:path];
    [self.selectedAssetURLs addObject:path];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

